package com.bishe.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.bishe.pojo.Clientinfo;
import com.bishe.pojo.Message;
import com.bishe.pojo.User;
import com.bishe.serivce.IMessageService;
import com.bishe.utils.EcoBootException;
import com.bishe.utils.Result;
import com.bishe.utils.SqlQueryUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 消息控制层
 * @date 2022/03/02 40:11:43
 */
@RestController
@RequestMapping("/message")
@Api(tags = "消息")
@CrossOrigin
public class MessageController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private IMessageService messageService;

    @ApiOperation("消息列表")
    @GetMapping("/getMessage")
    public Result getMessage(){

        List<Message> list = new SqlQueryUtils<>(Message.class, jdbcTemplate)
                .orderByDesc(Message::getCreateTime) //创建时间倒叙排序
                .getList();

        return Result.ok(list);
    }


    @ApiOperation("根据id删除")
    @DeleteMapping("delete/{id}")
    public Result deleteById(@PathVariable String id){
        if (StrUtil.isEmpty(id)){
            throw new EcoBootException("id不能为空");
        }

        messageService.deleteById(id);
        return Result.ok("删除成功");
    }

    @ApiOperation("获取今日代办消息")
    @GetMapping("/getDayMessage")
    public Result getDayMessage(){
        //获取当天开始时间
        Date dateTime = DateUtil.beginOfDay(new Date());
        //获取当天结束时间
        Date endOfDay = DateUtil.endOfDay(new Date());
        //查询当天数据
        List<Message> list = new SqlQueryUtils<Message>(Message.class, jdbcTemplate)
                .eq(Message::getIsCheck,"0")  //没有查看过
                .maxThan(Message::getMessageTime, dateTime, false)
                .minThan(Message::getMessageTime, endOfDay, false)
                .getList();
        //创建时间倒叙排序
        list = list.stream().sorted(Comparator.comparing(Message::getCreateTime).reversed()).collect(Collectors.toList());

        return Result.ok(list);
    }

    @ApiOperation("查看消息")
    @GetMapping("/lookMessage/{id}")
    public Result lookMessage(@PathVariable("id") String id){
        //根据id、查询
        Message one = new SqlQueryUtils<>(Message.class, jdbcTemplate).eq(Message::getId, id)
                .getOne();
        if (one == null){
            throw  new EcoBootException("没有此消息！");
        }
        //点击过
        one.setIsCheck(1);
        messageService.updateById(one);
        return Result.ok();
    }
}
